<template>
  <div class="video-edit-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑视频' : '上传视频' }}</span>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="video-form"
      >
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入视频标题" />
        </el-form-item>
        
        <el-form-item label="视频描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入视频描述"
          />
        </el-form-item>
        
        <el-form-item label="封面图片" prop="cover">
          <el-upload
            class="cover-uploader"
            action="/api/admin/upload/image"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
          >
            <el-image
              v-if="form.cover"
              :src="form.cover"
              class="preview-cover"
              fit="cover"
            />
            <div v-else class="upload-placeholder">
              <el-icon><el-icon-plus /></el-icon>
              <div class="upload-tip">上传封面</div>
            </div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="视频文件" prop="url" v-if="!isEdit || !form.url">
          <el-upload
            class="video-uploader"
            action="/api/admin/video/upload"
            :show-file-list="false"
            :on-progress="handleVideoProgress"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload"
            :on-error="handleVideoError"
          >
            <div v-if="videoUploading" class="uploading-progress">
              <el-progress type="circle" :percentage="uploadPercent" />
              <div class="progress-text">上传中 {{ uploadPercent }}%</div>
            </div>
            <div v-else-if="form.url" class="video-preview">
              <video :src="form.url" class="video-player" controls></video>
            </div>
            <div v-else class="upload-placeholder video-placeholder">
              <el-icon><el-icon-upload /></el-icon>
              <div class="upload-tip">点击上传视频</div>
              <div class="upload-hint">支持MP4, MOV, AVI格式, 最大500MB</div>
            </div>
          </el-upload>
        </el-form-item>
        
        <el-form-item v-if="isEdit && form.url" label="视频预览">
          <div class="video-preview">
            <video :src="form.url" class="video-player" controls></video>
          </div>
        </el-form-item>
        
        <el-form-item label="发布状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="发布"
            inactive-text="未发布"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting" :disabled="videoUploading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus as ElIconPlus, Upload as ElIconUpload } from '@element-plus/icons-vue'
import { getVideoDetail, createVideo, updateVideo } from '../../api/video'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)
const videoUploading = ref(false)
const uploadPercent = ref(0)

// 判断是编辑还是上传新视频
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  title: '',
  description: '',
  cover: '',
  url: '',
  status: 1, // 默认发布
  duration: 0
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入视频标题', trigger: 'blur' }],
  cover: [{ required: true, message: '请上传视频封面', trigger: 'change' }],
  url: [{ required: true, message: '请上传视频文件', trigger: 'change' }]
}

// 获取视频详情
const getDetail = async (id) => {
  try {
    const res = await getVideoDetail(id)
    if (res.code === 200 && res.data) {
      const data = res.data
      form.id = data.id
      form.title = data.title
      form.description = data.description || ''
      form.cover = data.cover
      form.url = data.url
      form.status = data.status
      form.duration = data.duration
    } else {
      ElMessage.error('获取视频信息失败')
    }
  } catch (error) {
    console.error('获取视频详情失败:', error)
    ElMessage.error('获取视频详情失败')
  }
}

// 封面上传前验证
const beforeCoverUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传封面只能是 JPG 或 PNG 格式!')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('上传封面大小不能超过 2MB!')
    return false
  }
  
  return true
}

// 封面上传成功回调
const handleCoverSuccess = (response) => {
  if (response.code === 200 && response.data) {
    form.cover = response.data.url
  } else {
    ElMessage.error('封面上传失败')
  }
}

// 视频上传前验证
const beforeVideoUpload = (file) => {
  const isMP4 = file.type === 'video/mp4'
  const isMOV = file.type === 'video/quicktime'
  const isAVI = file.type === 'video/x-msvideo'
  const isLt500M = file.size / 1024 / 1024 < 500

  if (!isMP4 && !isMOV && !isAVI) {
    ElMessage.error('上传视频只能是 MP4/MOV/AVI 格式!')
    return false
  }
  
  if (!isLt500M) {
    ElMessage.error('上传视频大小不能超过 500MB!')
    return false
  }
  
  videoUploading.value = true
  uploadPercent.value = 0
  return true
}

// 视频上传进度回调
const handleVideoProgress = (event) => {
  uploadPercent.value = Math.round((event.loaded / event.total) * 100)
}

// 视频上传成功回调
const handleVideoSuccess = (response) => {
  videoUploading.value = false
  if (response.code === 200 && response.data) {
    form.url = response.data.url
    form.duration = response.data.duration || 0
    ElMessage.success('视频上传成功')
  } else {
    ElMessage.error('视频上传失败')
  }
}

// 视频上传失败回调
const handleVideoError = () => {
  videoUploading.value = false
  ElMessage.error('视频上传失败')
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(valid => {
    if (!valid) return
    
    submitting.value = true
    const submitData = { ...form }
    
    // 判断是编辑还是新增
    const request = isEdit.value 
      ? updateVideo(form.id, submitData) 
      : createVideo(submitData)
    
    request.then(res => {
      if (res.code === 200) {
        ElMessage.success(`${isEdit.value ? '更新' : '上传'}视频成功`)
        goBack()
      } else {
        ElMessage.error(res.message || `${isEdit.value ? '更新' : '上传'}视频失败`)
      }
    }).catch(error => {
      console.error(`${isEdit.value ? '更新' : '上传'}视频失败:`, error)
      ElMessage.error(`${isEdit.value ? '更新' : '上传'}视频失败`)
    }).finally(() => {
      submitting.value = false
    })
  })
}

// 返回列表页
const goBack = () => {
  router.push('/video/list')
}

// 初始化
onMounted(() => {
  // 如果是编辑模式，获取视频详情
  if (isEdit.value) {
    getDetail(route.params.id)
  }
})
</script>

<style scoped>
.video-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-form {
  max-width: 800px;
}

.cover-uploader, .video-uploader {
  text-align: center;
}

.preview-cover {
  width: 200px;
  height: 120px;
  display: block;
  margin-bottom: 10px;
  object-fit: cover;
}

.upload-placeholder {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fbfdff;
}

.upload-placeholder:hover {
  border-color: #409EFF;
}

.upload-tip {
  font-size: 14px;
  color: #606266;
  margin-top: 10px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.video-placeholder {
  width: 100%;
  height: 240px;
}

.video-preview {
  width: 100%;
  margin-bottom: 10px;
}

.video-player {
  max-width: 100%;
  max-height: 400px;
}

.uploading-progress {
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.progress-text {
  margin-top: 10px;
  color: #606266;
}
</style> 